const router = require("koa-router")();
const DB = require("../../module/db");
const sd = require("silly-datetime");
const crypto = require("crypto");

router.get("/", async (ctx) => {
    ctx.body = "review首页";

}).post("/addCollection", async (ctx) => {
    let link = ctx.request.body.link
    let projectId = ctx.request.body.projectId
    let userId = ctx.request.body.userId
    let data1 = await DB.find('review', {"link": link})
    if (data1.length === 0) {
        ctx.body = {
            type: 0,
            info: "无此审验项目"
        }
    } else {
        let list = data1[0].userId
        let flag = list.some(function (x) {
            return x === userId
        })
        if (flag) {
            ctx.body = {
                type: 0,
                info: "您已经有此审验项目了"
            }
        } else {
            let data2 = await DB.addArray("project", {"_id": DB.getObjectId(projectId)}, {"collections": data1[0]._id})
            let data3 = await DB.addArray('review', {'_id': data1[0]._id}, {'userId': userId})
            if (data2.result.ok && data3.result.ok)
                ctx.body = {
                    type: 1,
                    info: data1
                }
            else
                ctx.body = {
                    type: 0,
                    info: "添加失败"
                }
        }
    }

}).post("/getCollections", async (ctx) => {
    let list = ctx.request.body.collections
    let projectId = ctx.request.body.projectId
    let list2 = []
    for (let i = 0; i < list.length; i ++) {
        let data = await DB.find('review', {"_id": DB.getObjectId(list[i])})
        if (data.length > 0)
            list2.push(data[0])
        else
            await DB.deleteArray('project', {"_id": DB.getObjectId(projectId)}, {"collections": DB.getObjectId(list[i])})
    }
    ctx.body = list2;

}).post("/deleteCollection", async (ctx) => {
    let reviewId = ctx.request.body.id
    let projectId = ctx.request.body.projectId
    let userId = ctx.request.body.userId
    let data1 = await DB.deleteArray('project', {"_id": DB.getObjectId(projectId)}, {"collections": DB.getObjectId(reviewId)})
    let data2 = await DB.deleteArray('review', {"_id": DB.getObjectId(reviewId)}, {"userId": userId})
    if (data1.result.ok && data2.result.ok)
        ctx.body = {
            type: 1,
            info: ""
        }
    else
        ctx.body = {
            type: 0,
            info: "删除失败"
        }

});


module.exports = router.routes();
